package utils.aria2;

import com.alibaba.fastjson.JSONObject;
import entity.*;
import lombok.extern.slf4j.Slf4j;
import okhttp3.WebSocket;
import utils.cli.CLIUtil;
import utils.json.InitConfig;
import utils.okhttp.OkHttpUtil;

import java.util.Collections;
import java.util.Objects;

/**
 * Aria2工具类
 * 远程连接Aria2服务器，实现推送下载任务功能。
 */
@Slf4j
public class Aria2Util {
    private static final WebSocket webSocket = OkHttpUtil.getInstance().getWebSocket();
    private static final Aria2Util instance = new Aria2Util();
    private static final ConfigFile configFile = InitConfig.getInstance().getConfig();

    private Aria2Util() {
    }

    public static Aria2Util getInstance() {
        return instance;
    }

    private static void send(String json) {
        webSocket.send(json);
    }

    /**
     * 推送下载任务给远程Aria2服务器
     *
     * @param fileUrls 下载文件集合
     * @param option   下载参数-可选项
     * @return 返回Aria2对象
     */
    public Aria2 push(String[] fileUrls, Aria2Option... option) {
        Aria2 aria2 = new Aria2();
        aria2.setMethod(Aria2.METHOD_ADD_URI);
        if (!Objects.equals(configFile.getAria2().getToken(), "")) {
            aria2.addParam("token:" + configFile.getAria2().getToken());
        }
        aria2.addParam(fileUrls);
        aria2.addParam(option);
        String json = parserJSON(JSONObject.toJSONString(aria2));
        send(json);
        return aria2;
    }

    /**
     * 根据VideoItem获取真实下载链接，并推送到远程Aria2服务器
     *
     * @param item VideoItem对象
     * @return 返回Aria2对象
     */
    public Aria2 pushByVideoItem(VideoItem item) {
        YouGetVideo youGetVideo = CLIUtil.getVideoRealLink(item.getLink());
        Aria2Option option = new Aria2Option();
        option.setDir(configFile.getAria2().getPath());
        option.setOut(youGetVideo.getTitle() + ".mp4");
        option.setReferer(youGetVideo.getExtra().getReferer());
        option.setHeader(Collections.singletonList(youGetVideo.getExtra().getUa()));
        return push(new String[]{youGetVideo.getStreams().getFlv().getSrc().get(0)}, option);
    }

    /**
     * 处理JSON字符串，使其符合Aria2的请求格式
     *
     * @param json 处理前的json字符串
     * @return 格式化后的json字符串
     */
    private static String parserJSON(String json) {
        int startIndex = json.indexOf(",[{");
        return json.substring(0, startIndex + 1) + json.substring(startIndex + 2, json.length() - 2) +
                "}";
    }
}
